﻿#include "textscaner.h"
#include "ui_textscaner.h"

TextScaner::TextScaner(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TextScaner)
{
    ui->setupUi(this);
    table=TD_TOPIC;
    category=UKN_CATEGORY;
}

TextScaner::~TextScaner()
{
    delete ui;
}

void TextScaner::on_btn_pick_clicked()
{
    QString path=QFileDialog::getExistingDirectory(this,QStringLiteral("选择目录"));
    if(path.isEmpty())
        return;

    ui->path->setText(path);
}

bool TextScaner::addItem(const QString &label, const QString &detail)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (category,label,detail) values (?,?,?)")
                  .arg(table));
    query.addBindValue(category);
    query.addBindValue(label);
    query.addBindValue(detail);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void TextScaner::on_btn_scan_clicked()
{
    QString path=ui->path->text();
    if(path.isEmpty())
        return;

    QDir dir(path);
    if(!dir.exists())
        return;

    category=dir.dirName();
    if(category.isEmpty())
        category=UKN_CATEGORY;

    QFileInfoList fileInfoList=dir.entryInfoList(QStringList() << "*.txt",QDir::Files);
    if(fileInfoList.isEmpty())
        return;

    foreach (QFileInfo fileInfo, fileInfoList) {
        QString label=fileInfo.baseName();
        QString filePath=fileInfo.filePath();
        QFile file(filePath);
        if(!file.open(QFile::ReadOnly | QFile::Text))
            continue;
        else
        {
            QTextStream text(&file);
            QString detail=text.readAll();
            if(addItem(label,detail))
                ui->detail->appendPlainText(label + QStringLiteral(" 已添加"));
            else
                ui->detail->appendPlainText(label + QStringLiteral(" 添加失败"));
            file.close();
        }
    }

}
